import { shallowMount } from '@vue/test-utils';
import LoginComponent from '@/components/LoginComponent.vue';
import axios from 'axios';
import api from '@/api';


jest.mock('axios');

describe('LoginComponent', () => {
  it('should call login method when form is submitted', async () => {
    const wrapper = shallowMount(LoginComponent);

    // 模拟用户输入
    wrapper.setData({ username: 'testuser', password: 'password' });

    // 模拟 axios 请求
    axios.post.mockResolvedValueOnce({
      data: {
        token: 'mocked_token',
        message: 'Login successful'
      }
    });

    // 触发登录方法
    await wrapper.find('form').trigger('submit');

    // 检查是否发送了正确的请求
    expect(api.post).toHaveBeenCalledWith('/user/login', {
      username: 'testuser',
      password: 'password'
    });

    // 检查是否有消息提示登录成功
    expect(wrapper.text()).toContain('Login successful');
  });

  it('should show error message on failed login', async () => {
    const wrapper = shallowMount(LoginComponent);

    // 模拟用户输入
    wrapper.setData({ username: 'testuser', password: 'wrongpassword' });

    // 模拟失败的 axios 请求
    axios.post.mockRejectedValueOnce(new Error('Login failed'));

    // 触发登录方法
    await wrapper.find('form').trigger('submit');

    // 检查是否有错误消息提示
    expect(wrapper.text()).toContain('Login failed');
  });
});